<template>
  <div class="modal" ref="modal" tabindex="-1" role="dialog" data-show="true" data-backdrop="static">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body" style="height: 400px;">
          <div class="row" style="height: 100%;">
            <div class="col-sm-4">
              <div class="profile-user-img img-responsive img-circle" style="width: 150px;height: 150px;margin-top: 50%;">
                <img :src="previews.url" :style="previews.img">
              </div>
            </div>
            <div class="col-sm-8">
              <div style="height: 340px">
                <vueCropper
                  ref="cropper"
                  :img="option.img"
                  :outputSize="option.size"
                  :outputType="option.outputType"
                  :autoCropWidth="150"
                  :autoCropHeight="150"
                  autoCrop
                  fixedBox
                  @realTime="realTime"
                ></vueCropper>
              </div>
              <div style="padding: 6px 0;">
                <label class="pull-left btn btn-default" for="uploads">选择图片</label>
                <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)">
                <bs-button icon="fa fa-rotate-right" @click="rotateRight" class="pull-right" style="margin-left: 5px;"></bs-button>
                <bs-button icon="fa fa-rotate-left" @click="rotateLeft" class="pull-right"></bs-button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <bs-button data-dismiss="modal" class="pull-left" :disabled="loading" html-type="button">取消</bs-button>
          <bs-button icon="fa fa-upload" class="pull-right" type="primary" html-type="submit" :loading="loading" @click="onUploadImg">确认修改</bs-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import VueCropper from 'vue-cropper';
  import utils from '@/utils';

  export default {
    name: 'ProfileAvatar',
    components: {VueCropper},
    mixins: [utils.ModalMixins],
    data() {
      return {
        loading: false,
        previews: {},
        option: {
          outputType: 'jpeg',
          size: 1,
          img: ''
        }
      };
    },
    methods: {
      realTime(data) {
        this.previews = data;
      },
      uploadImg(e) {
        var file = e.target.files[0];
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
          return false;
        }
        var reader = new FileReader();
        reader.onload = (e) => {
          let data;
          if (typeof e.target.result === 'object') {
            data = window.URL.createObjectURL(new Blob([e.target.result]));
          } else {
            data = e.target.result;
          }
          this.option.img = data;
        };
        reader.readAsArrayBuffer(file);
      },
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      onUploadImg() {
        this.$refs.cropper.getCropData(data => {
          const file = this.convertBase64UrlToBlob(data);
          const formData = new FormData();
          formData.append('file', file);
          this.$api('common.uploadAvatar').invoke(formData, {
            headers: {'Content-Type': 'multipart/form-data'}
          }).then(({data}) => {
            this.$store.commit('UPDATE_USER', data);
            this.$router.back();
          });
        });
      },
      convertBase64UrlToBlob(urlData) {
        const bytes = window.atob(urlData.split(',')[1]);
        const ab = new ArrayBuffer(bytes.length);
        const ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
          ia[i] = bytes.charCodeAt(i);
        }
        return new Blob([ab], {type: 'image/jpeg'});
      }
    }
  };
</script>

<style scoped>
  .profile-user-img {
    overflow: hidden;
  }
</style>
